package cn.bitkit.tools.common;

/**
 * 相似度计算工具类
 */
public class SimilarityUtil {

    public static double calculateSimilarity(String s1, String s2) {
        // 如果有一个字符串为空，则返回0
        if (s1 == null || s2 == null) {
            return 0;
        }
        // 如果两个字符串相等，则返回1
        if (s1.equals(s2)) {
            return 1.0;
        }
        // 计算Levenshtein距离
        int distance = levenshteinDistance(s1, s2);
        // 计算相似度：1 - (距离 / 最大长度)
        int maxLength = Math.max(s1.length(), s2.length());
        // 避免除以零
        if (maxLength == 0) {
            return 1.0;
        }
        return 1.0 - ((double) distance / maxLength);
    }

    private static int levenshteinDistance(String s1, String s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        // 创建距离矩阵
        int[][] dp = new int[len1 + 1][len2 + 1];
        // 初始化
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j;
        }
        // 填充矩阵
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                int cost = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? 0 : 1;
                dp[i][j] = Math.min(
                        Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1),
                        dp[i - 1][j - 1] + cost
                );
            }
        }
        return dp[len1][len2];
    }
}
